<template>
  <div>
    <el-card class="search-card" v-loading="formLoading">
      <BasicForm
        v-if="!formLoading"
        ref="formData"
        formItemWidth="120px"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
        <el-row slot="extensionActions" type="flex">
          <el-button type="primary" @click="exportToDoList" :loading="exportLoading" v-if="showBtn('导出')">导出</el-button>
        </el-row>
      </BasicForm>
    </el-card>
    <el-card class="table-card">
      <BasicTable
        showPagination
        isCustomSort
        showActionCol
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="480"
        :actionRender="actionRender"
        :actionColWidth="160"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :tableRowClassName="setTableRowClassName"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      />
    </el-card>
    <DisposeDialog :visible.sync="disposeDialogVisible" :rowData="rowData" @disposeCallback="disposeCallback" />
    <AuditDialog :visible.sync="auditDialogVisible" :rowData="rowData" @getTableData="getTableData" />
    <AdjustPrice :visible.sync="adjustPriceVisible" />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/skusTable';
import AuditDialog from './components/AuditDialog';
import DisposeDialog from './components/DisposeDialog';
import AdjustPrice from './components/AdjustPrice';
import skusPage from '@/mixins/commodity/skusPage';
import { initFormItemList, getTableColumns } from './constants';
import { setAuthBtnId, handleOpenNewPage } from '@/utils/bizUtils';
import { queryPriceCycleToDoListService } from '@/api/finance/priceCycleManage/toDoList';
import { queryAreaListService, queryBelongDepartmentService } from '@/api/public';
import { ApiRequestExportTable } from '@api/basePage';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    BasicTable,
    AuditDialog,
    DisposeDialog,
    AdjustPrice
  },
  data () {
    return {
      rowData: {},
      disposeDialogVisible: false, // 处理
      auditDialogVisible: false, // 审核
      adjustPriceVisible: false, // 调价
      formItemList: initFormItemList(),
      formLoading: false,
      formData: {
        state: '',
        overdueState: '',
        statisticsDate: '',
        supplyNoOrName: '',
        authDepartmentNo: '',
        manageAreaUuid: '',
        handlerName: '',
        recordNo: '',
        adjustPriceState: ''
      },
      tableInfo: {
        list: [],
        columns: getTableColumns(this),
        loading: false,
        selection: []
      },
      pageSizes: [10, 100, 1000],
      exportLoading: false
    }
  },
  mounted () {
    this.initParams()
    this.initSearchOptions()
    this.getTableData()
  },
  methods: {
    initParams () {
      const { state, overdueDays } = this.$route.query;
      if (state) {
        this.formData.state = state;
      }
      // 超预警日期
      if (overdueDays) {
        this.formData.overdueDays = overdueDays;
      }
    },
    actionRender (h, { row }) {
      // 处理状态：1待处理/2调价中/3待审核/4已处理
      return (
        <div class="table-action">
          <el-button size="mini" type="text" disabled={!this.showBtn('供货信息')} onClick={() => this.handleViewSupplyInfo(row)}>供货明细</el-button>
          <el-button size="mini" disabled={!this.showBtn('处理') || row.state != 1} type="text" onClick={() => this.handleDisposeTodo(row)}>处理</el-button>
          <el-button size="mini" disabled={!this.showBtn('审核') || row.state != 3} type="text" onClick={() => this.handleAuditTodo(row)}>审核</el-button>
        </div>
      );
    },
    // 获取表单查询入参
    getSearchFormParams () {
      const [startDate = '', endDate = ''] = this.formData.statisticsDate || [];
      const formData = {
        startDate,
        endDate,
        ..._.omit(this.formData, 'statisticsDate'),
      }
      return {
        ...this.paginationParams,
        ...formData,
      }
    },
    // 获取表格数据
    async getTableData () {
      setAuthBtnId();
      const res = await queryPriceCycleToDoListService(
        this.getSearchFormParams(),
        state => { this.tableInfo.loading = state }
      );
      if (res?.retData) {
        this.tableInfo.list = res.retData.results;
        this.total = res.retData.totalNum;
      }
    },
    // 初始化下拉数据
    initSearchOptions () {
      this.formLoading = true;
      Promise.all([
        this.getBelongDepartmentData(),
        this.getBusinessAreaList(),
      ].map(item => item.catch(e => {
        console.log('错误信息' + e)
      }))).then(([departmentData, areaData]) => {
        this.formItemList = initFormItemList(departmentData, areaData)
        this.formLoading = false;
      }).catch(() => {
        this.formLoading = false;
      })
    },
    // 获取归属部门
    async getBelongDepartmentData () {
      const res = await queryBelongDepartmentService({});
      if (res?.retData) {
        return res.retData;
      }
    },
    // 获取业务区域
    async getBusinessAreaList () {
      const res = await queryAreaListService({});
      if (res?.retData) {
        const areaList = res.retData.map(item => {
          return {
            value: item.areaCode,
            label: item.areaName
          }
        })
        return areaList;
      }
    },
    // 供货状态
    handleViewSupplyInfo (row) {
      handleOpenNewPage(this, { name: 'todoSupplyDetail', query: { recordNo: row.recordNo } })
    },
    // 处理待办
    handleDisposeTodo (row) {
      this.rowData = row;
      this.disposeDialogVisible = true;
    },
    // 审核待办
    handleAuditTodo (row) {
      this.rowData = row;
      this.auditDialogVisible = true;
    },
    // 处理回调
    disposeCallback (row) {
      // 调整售价或进价
      if (row.adjustPriceState == 1) {
        this.adjustPriceVisible = true;
      } else {
        this.getTableData()
      }
    },
    // 表格背景色设置 是否超期 是 粉色提示
    setTableRowClassName ({ row, rowIndex }) {
      if (row.overdueState == 1) {
        return 'error-row';
      }
      return '';
    },
    exportToDoList () {
      this.exportLoading = true;
      setAuthBtnId();
      ApiRequestExportTable('/sysback/product/priceManagementCycle/toDoMainList/export', 'post', this.getSearchFormParams(), false).then(res => {
        const blob = new Blob([res], {
          type: 'application/octet-stream'
        });
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '价格管理周期代办列表.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
        this.$message.error('导出失败');
      });
    }
  }
}
</script>
